package com.winning.bi.jms;
/**
 * 
 * @author 张大川
 * 
 *  
 * ActiveMQ JMS消息处理 
 * 生产者
 */

import java.io.Serializable;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SendMessageUtils {
	private static Logger log = LoggerFactory.getLogger(SendMessageUtils.class);
	public static String username;
	public static String password;
	public static String url;
	Connection connection;
	// static
	//
	// {
	//
	// try {
	// Configuration configuration = new
	// PropertiesConfiguration("config/jms.properties");
	// password = configuration.getString("password");
	// username = configuration.getString("username");
	// url = configuration.getString("url");
	// } catch (ConfigurationException e) {
	// log.error(e.getMessage());
	// }
	//
	// }
	//
	// private static final class FactoryInstance {
	// public static Connection con;
	// static {
	// try {
	// con = new ActiveMQConnectionFactory(SendMessageUtils.username,
	// SendMessageUtils.password,
	// SendMessageUtils.url).createConnection();
	// } catch (JMSException e) {
	// log.error(e.getMessage());
	// }
	// }
	//
	// }

	public SendMessageUtils() throws ConfigurationException {
		Configuration configuration = new PropertiesConfiguration("config/jms.properties");
		password = configuration.getString("password");
		username = configuration.getString("username");
		url = configuration.getString("url");

	}

	public void close() throws JMSException {
		connection.close();
	}

	public void sendMessage(String queueName, Serializable object) throws JMSException {
		try {
			connection = new ActiveMQConnectionFactory(username, password, url).createConnection();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			connection.start();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 创建session
		Session session = null;
		try {
			session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 创建一个名称为HelloWorld的消息队列
		Queue destination = session.createQueue(queueName);
		// 创建消息生产者
		MessageProducer messageProducer = session.createProducer(destination);
		messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);// 持久化消息
		
		ObjectMessage message = session.createObjectMessage();
		message.setObject(object);
		messageProducer.send(message);
		session.commit();
		// SendMessageUtils.close();
	}

}
